package com.xh.jf_blog.service.impl;

import com.xh.jf_blog.bean.Code;
import com.xh.jf_blog.common.exception.RTException;
import com.xh.jf_blog.common.util.MessageUtil;
import com.xh.jf_blog.common.util.R;
import com.xh.jf_blog.mapper.CodeMapper;
import com.xh.jf_blog.service.CodeService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Random;

/**
 * @Author PangJunjie
 * @Date 2024/1/31/031
 */
@Service
@Transactional
public class CodeServiceImpl implements CodeService {
    @Autowired
    private CodeMapper codeMapper;

    public void saveCode(Code code) {
        Date d = new Date();
        d.setMinutes(d.getMinutes() + 5);
        code.setExpires(d);
        codeMapper.insertSelective(code);
    }

    public boolean checkCode(Code code) {
        Code c = codeMapper.selectByPrimaryKey(code.getUuid());
        if (c == null) {
            throw new RTException("验证码不存在！");
        }
        /*忽略大小写匹配*/
        if (!c.getCode().equalsIgnoreCase(code.getCode())) {
            throw new RTException("验证码错误！");
        }
        if (c.getExpires().getTime() < System.currentTimeMillis()) {
            throw new RTException("验证过失效！");
        }
        codeMapper.deleteByPrimaryKey(code.getUuid());//验证成功的则删除
        return true;
    }

    public void clear() {
        Code code = new Code();
        code.setExpires(new Date());
        codeMapper.delete(code);
    }

    public R sendMsg(String phone) {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int r = random.nextInt(10);
            code += r;
        }
        String response = MessageUtil.sendMsg(phone, code);
        JSONObject jsonObject = JSONObject.fromObject(response);
        int error_code = jsonObject.getInt("error_code");
        if (error_code == 0) {
            System.out.println("调用接口成功");
            JSONObject result = jsonObject.getJSONObject("result");
            String sid = result.getString("sid");
            Code codeBean = new Code();
            codeBean.setUuid(sid);
            codeBean.setCode(code);
            Date d = new Date();
            d.setMinutes(d.getMinutes() + 5);
            codeBean.setExpires(d);

            codeMapper.insertSelective(codeBean);
            return R.ok(sid);
        } else {
            System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            return R.error(jsonObject.getString("reason"));
        }
    }
}
